package com.atguigu.tingshu.account.service.impl;

import com.atguigu.tingshu.account.mapper.RechargeInfoMapper;
import com.atguigu.tingshu.account.mapper.UserAccountDetailMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.RechargeInfoService;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.atguigu.tingshu.vo.account.RechargeInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.UUID;

@Service
@SuppressWarnings({"all"})
public class RechargeInfoServiceImpl extends ServiceImpl<RechargeInfoMapper, RechargeInfo> implements RechargeInfoService {

	@Autowired
	private RechargeInfoMapper rechargeInfoMapper;

	@Autowired
	private UserAccountMapper userAccountMapper;

	@Autowired
	private UserAccountDetailMapper userAccountDetailMapper;

	@Autowired
	private UserAccountService userAccountService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void rechargePaySuccess(String orderNo) {
		//	根据订单编号查询数据;
		RechargeInfo rechargeInfo = rechargeInfoMapper.selectOne(new LambdaQueryWrapper<RechargeInfo>().eq(RechargeInfo::getOrderNo, orderNo));
		//	判断当前对象状态;
		if (null != rechargeInfo && rechargeInfo.getRechargeStatus().equals(SystemConstant.ORDER_STATUS_PAID)){
			return;
		}
		rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_PAID);
		this.rechargeInfoMapper.updateById(rechargeInfo);
		//	给账户增加余额;
		userAccountMapper.addUserAccount(rechargeInfo.getUserId(),rechargeInfo.getRechargeAmount());
		//	记录账户资金明细;
		userAccountService.addUserAccountDetail(rechargeInfo.getUserId(),"充值:"+rechargeInfo.getRechargeAmount(),SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT,rechargeInfo.getRechargeAmount(),orderNo);
	}

	@Override
	public String submitRecharge(RechargeInfoVo rechargeInfoVo, Long userId) {
		//	保存数据;
		RechargeInfo rechargeInfo = new RechargeInfo();
		//	属性赋值;
		rechargeInfo.setUserId(userId);
		String orderNo = UUID.randomUUID().toString().replaceAll("-", "");
		rechargeInfo.setOrderNo(orderNo);
		rechargeInfo.setRechargeAmount(rechargeInfoVo.getAmount());
		rechargeInfo.setPayWay(rechargeInfoVo.getPayWay());
		rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_UNPAID);
		rechargeInfoMapper.insert(rechargeInfo);
		//	返回数据
		return orderNo;
	}
}
